import fly from 'flyio';
import { baseURL } from './config';

// 全局 axios 默认配置
fly.config = {
    timeout: 50000,
    headers: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
    },
    baseURL
};

//POST传参序列化(添加请求拦截器)
fly.interceptors.request.use(request => {
    return request;
});

//添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
    response => {
        //只将请求结果的data字段返回
        return response.data;
    },
    err => {
        //发生网络错误后会走到这里
        //return Promise.resolve("ssss")
    }
);

const request = (url, data, method) => {
    console.log('请求参数');
    console.log(data);
    return new Promise((resolve, reject) => {
        fly.request({
            url,
            method,
            data
        })
            .then(response => {
                const data = JSON.parse(response);
                if (data.code) resolve(data);
                else reject(data.msg);
            })
            .catch(error => {
                reject(error);
            });
    });
};

export default request;
